package com.nic.view.util;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;

import com.nic.view.R;
import com.nic.view.ViewConfig;

import java.io.File;
import java.util.List;
import java.util.Locale;

/**
 * 打开附件
 */
public class AndroidFileUtil {


    public static Intent openFile(String filePath) {

        System.out.println("打开的文件路径 : " + filePath);
        File file = new File(filePath);
        if (!file.exists()) {
            return null;
        }
        /* 取得扩展名 */
        String fileName = file.getName();
        String end = fileName.substring(file.getName().lastIndexOf(".") + 1,
                file.getName().length()).toLowerCase();
        /* 依扩展名的类型决定MimeType */
        Intent intent = null;
        if (end.equals("jpg") || end.equals("gif") || end.equals("png")
                || end.equals("jpeg") || end.equals("bmp")) {
            intent = getImageFileIntent(filePath);
        } else if (end.equals("ppt")) {
            intent = getPptFileIntent(filePath);
        } else if (end.equals("xls") || end.equals("xlsx") || end.equals("xml")) {
//          intent = getExcelFileIntent(filePath);
            intent = getExcelFileIntent(filePath);
        } else if (end.equals("doc")) {
            intent = getWordFileIntent(filePath);
        } else if (end.equals("docx")) {
            intent = getWordFileIntent(filePath);
        } else if (end.equals("pdf")) {
            intent = getPdfFileIntent(filePath);
        } else if (end.equals("chm")) {
            intent = getChmFileIntent(filePath);
        } else if (end.equals("txt")) {
            intent = getTextFileIntent(filePath, false);
        }
        if (end.equals("mp4")) {
            intent = getMp4FileIntent(filePath);
        }
        return intent;
    }


    // 播放音乐
    public static Intent openMusic(String filePath) {

        File file = new File(filePath);
        System.out.println("打开的文件路径 : " + filePath);
        if (!file.exists()) {
            return null;
        }
        /* 取得扩展名 */
        String fileName = file.getName();
        String end = fileName.substring(file.getName().lastIndexOf(".") + 1,
                file.getName().length()).toLowerCase();
        /* 依扩展名的类型决定MimeType */
        Intent intent = null;
        intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        Uri uri = Uri.fromFile(new File(filePath));
        Uri uri = uriString(filePath);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.setDataAndType(uri, "audio/*");
        return intent;
    }


    public static Intent getMp4FileIntent(String param) {
        return getMp4FileIntent(param, false);
    }

    public static Intent getMp4FileIntent(String param, boolean play_mute) {
        Intent intent = new Intent("android.intent.action.VIEW");
        if (isLjtVideoPlayerAvilible(ViewConfig.applicationContext)) {
            intent.setPackage("com.Ljt.videoplayer");
        }
        intent.putExtra("video_rotation", "90");//竖屏播放
        intent.putExtra("play_mute", play_mute);//true --静音播放,false -- 正常播放
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        Uri uri = uriString(param);
        intent.setDataAndType(uri, "video/*");
        return intent;
    }

    public static boolean isLjtVideoPlayerAvilible(Context context) {
        String mPackageName = "com.Ljt.videoplayer";
        PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (mPackageName.equals(pn)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static Intent getImageFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        Uri uri = Uri.fromFile(new File(param));
        Uri uri = uriString(param);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.setDataAndType(uri, "image/*");
        return intent;
    }

    // Android获取一个用于打开PPT文件的intent
    public static Intent getPptFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//      Uri uri = Uri.fromFile(new File(param));
        Uri uri = uriString(param);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
        return intent;
    }

    // Android获取一个用于打开Excel文件的intent
    public static Intent getExcelFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = uriString(param);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.setDataAndType(uri, "application/vnd.ms-excel");
//      Uri uri = Uri.fromFile(new File(param));
//      intent.setDataAndType(uri, "application/vnd.ms-excel");
        return intent;
    }

    // Android获取一个用于打开Word文件的intent
    public static Intent getWordFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//      Uri uri = Uri.fromFile(new File(param));
        Uri uri = uriString(param);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.setDataAndType(uri, "application/msword");
        return intent;
    }

    // Android获取一个用于打开CHM文件的intent
    public static Intent getChmFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        Uri uri = Uri.fromFile(new File(param));
        Uri uri = uriString(param);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.setDataAndType(uri, "application/x-chm");
        return intent;
    }

    // Android获取一个用于打开文本文件的intent
    public static Intent getTextFileIntent(String param, boolean paramBoolean) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (paramBoolean) {
            Uri uri1 = Uri.parse(param);
            intent.setDataAndType(uri1, "text/plain");
        } else {
//            Uri uri2 = Uri.fromFile(new File(param));
            Uri uri2 = uriString(param);
//            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.setDataAndType(uri2, "text/plain");
        }
        return intent;
    }

    // Android获取一个用于打开PDF文件的intent
    public static Intent getPdfFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//      Uri uri = Uri.fromFile(new File(param));
        Uri uri = uriString(param);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.setDataAndType(uri, "application/pdf");
        return intent;
    }

    public static Uri uriString(String param) {
        File storageDir = new File(param);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return ViewConfig.getFileProviderA7(ViewConfig.applicationContext, storageDir);
        }
        return Uri.fromFile(storageDir);
    }

    public static class MimeType {
        public static final String DOC = "application/msword";
        public static final String DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        public static final String XLS = "application/vnd.ms-excel application/x-excel";
        public static final String XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        public static final String XLSX2 = "application/x-excel";
        public static final String PPT = "application/vnd.ms-powerpoint";
        public static final String PPTX = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
        public static final String PDF = "application/pdf";
        public static final String MP4 = "video/mp4";
        public static final String M3U8 = "application/x-mpegURL";
        public static final String APK = "application/vnd.android.package-archive";
        public static final String TEXT = "text/plain";
        public static final String JPEG = "image/jpeg";
        public static final String PNG = "image/png";
        public static final String GIF = "image/gif";
        public static final String mid_midi_kar = "audio/midi";
        public static final String mp3 = "audio/mpeg";
        public static final String ogg = "audio/ogg";
        public static final String m4a = "audio/x-m4a";
        public static final String wav = "audio/x-wav";
        public static final String zip = "application/zip";


    }

    public static void openDirChooseFile(Activity activity, int requestCode, String[] mimeTypes) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        if (mimeTypes != null) {
            intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        }
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        // intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);//多选
        activity.startActivityForResult(intent, requestCode);
    }

    //
    public static void chooseFile(Activity activity, int requestCode) {
        String[] mimeTypes = activity.getResources().getStringArray(R.array.mineType);//{MimeType.DOC, MimeType.DOCX, MimeType.PDF, MimeType.PPT, MimeType.PPTX, MimeType.XLS, MimeType.XLSX, MimeType.XLSX2};
        openDirChooseFile(activity, requestCode, mimeTypes);
    }

    /**
     * 根据Uri获取文件的绝对路径，解决Android4.4以上版本Uri转换
     *
     * @param fileUri
     */
    @TargetApi(19)
    public static String getPath2uri(Activity context, Uri fileUri) {
        if (context == null || fileUri == null)
            return null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, fileUri)) {
            if (isExternalStorageDocument(fileUri)) {
                String docId = DocumentsContract.getDocumentId(fileUri);
                String[] split = docId.split(":");
                String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(fileUri)) {
                String id = DocumentsContract.getDocumentId(fileUri);
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(fileUri)) {
                String docId = DocumentsContract.getDocumentId(fileUri);
                String[] split = docId.split(":");
                String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } // MediaStore (and general)
        else if ("content".equalsIgnoreCase(fileUri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(fileUri))
                return fileUri.getLastPathSegment();
            return getDataColumn(context, fileUri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(fileUri.getScheme())) {
            return fileUri.getPath();
        }
        return null;
    }

    /**
     * Android4.4 （<19）以下版本获取uri地址方法
     *
     * @param context       上下文
     * @param uri           返回的uri
     * @param selection     条件
     * @param selectionArgs 值
     * @return uri文件所在的路径
     */
    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String[] projection = {MediaStore.Images.Media.DATA};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return URI权限是否为ExternalStorageProvider
     * Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return URI权限是否为google图片
     * Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return URI权限是否为DownloadsProvider.
     * Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return URI权限是否为MediaProvider.
     * Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    private static String getSuffix(File file) {
        if (file == null || !file.exists() || file.isDirectory()) {
            return null;
        }
        String fileName = file.getName();
        if (fileName.equals("") || fileName.endsWith(".")) {
            return null;
        }
        int index = fileName.lastIndexOf(".");
        if (index != -1) {
            return fileName.substring(index + 1).toLowerCase(Locale.US);
        } else {
            return null;
        }
    }

    /**
     * 获取文件mineType
     *
     * @param file
     * @return
     */
    public static String getMimeType(File file) {
        String suffix = getSuffix(file);
        if (suffix == null) {
            return "file/*";
        }
        String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(suffix);
        if (!TextUtils.isEmpty(type)) {
            return type;
        }
        return "file/*";
    }

    public static String getMimeType(String url) {
        if (url.equals("") || url.endsWith(".")) {
            return null;
        }
        int index = url.lastIndexOf(".");
        String suffix = null;
        if (index != -1) {
            suffix = url.substring(index + 1).toLowerCase(Locale.US);
        }
        if (suffix == null) {
            return "file/*";
        }
        String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(suffix);
        if (!TextUtils.isEmpty(type)) {
            return type;
        }
        return "file/*";
    }
//    public static void sendChooser(Activity activity, int requestCode){
//        File file =new File("/storage/emulated/0/com.ljkj.cordial.chat");
//        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.setDataAndType(ViewConfig.getFileProviderA7(activity, file), "*/*");
//        intent.addCategory(Intent.CATEGORY_DEFAULT);
//        activity.startActivityForResult(intent,requestCode);
//    }

}
